import {
  Controller,
  Post,
  Body,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import { ApiUseTags, ApiResponse, ApiOperation } from '@nestjs/swagger';

import { LoginDto } from './dtos/login.dto';
import { RegisterDto } from './dtos/register.dto';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service';
import { ApiException } from '@/common/exceptions/api.exception';
import { ApiErrorCode } from '@/common/enums/api-error-code.enum';
import { ApiResult } from '@/common/interceptors/result.interceptor';

@ApiUseTags('权限模块')
@Controller('auth')
export class AuthController {
  constructor(
    private authService: AuthService,
    private userService: UserService
  ) {}

  /**
   * 登录接口 并签发token
   * @param param 登录入参
   */
  @Post('login')
  @ApiOperation({
    title: '登录接口',
    description: '用于用户登录'
  })
  @ApiResponse({
    status: 201,
    description: 'The record has been successfully created.'
  })
  async loginIn(@Body() param: LoginDto): Promise<any> {
    const data = await this.userService.findUserByUserName(param.username);
    if (!data) {
      return new ApiResult({}, '用户不存在', false);
      // throw new ApiException('用户不存在', ApiErrorCode.USER_NOT_FIND, HttpStatus.BAD_REQUEST)
    }
    // 有数据  并且密码一致
    if (data.password !== param.password) {
      return new ApiResult({}, '用户名密码不正确', false);
    }
    // 签发证书
    const token = await this.authService.signIn({ username: data.username });

    return new ApiResult(token, '', true);
  }

  /**
   * 注册账号接口
   * @param param
   */
  @Post('register')
  @ApiOperation({
    title: '注册接口',
    description: '用于注册用户'
  })
  async register(@Body() param: RegisterDto): Promise<any> {
    const user = await this.userService.findUserByUserName(param.username);
    if (user) {
      return new HttpException('已经存在的用户', 403);
    }
    const newuser = await this.userService.createUser(param);
    return { code: 200, success: true };
  }
}
